<?php

namespace App\Http\Resources\Labaicai;

use Illuminate\Http\Resources\Json\JsonResource;

class CategoryResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        $arr = parent::toArray($request);
        $consumed = 0;
        $consumed_rate = 0;
        $carbon = $protein = $fat = 0;

        if (!empty($arr['daily_foods'])) {
            foreach ($arr['daily_foods'] as $k => $r) {
                $consumed += !empty($r['heat']) ? $r['heat'] * $r['pivot']['number'] : $r['pivot']['number'];
                $carbon += !empty($r['carbon']) ? $r['carbon'] * $r['pivot']['number'] : $r['pivot']['number'];
                $protein += !empty($r['protein']) ? $r['protein'] * $r['pivot']['number'] : $r['pivot']['number'];
                $fat += !empty($r['fat']) ? $r['fat'] * $r['pivot']['number'] : $r['pivot']['number'];
            }
        }
        if (!empty($consumed)) {
            $consumed_rate = $consumed / $arr['recommend_in_min'];
        }
        $arr['consumed_rate'] = ($consumed_rate * 100) > 1000 ? 100 : ($consumed_rate * 100);
        $arr['consumed'] = $consumed;
        $arr['carbon'] = $carbon;
        $arr['protein'] = $protein;
        $arr['fat'] = $fat;
        return $arr;
    }

}
